<template>
  <div class="knowledge-point-container">
    <!-- 顶部导航 -->
    <div class="header-section">
      <div class="header-content">
        <el-button type="text" @click="$router.push('/home/learning')" class="back-btn">
          <i class="el-icon-arrow-left"></i>
          返回学习中心
        </el-button>
        <h2 class="page-title">知识点练习</h2>
      </div>
    </div>

    <!-- 主要内容区域 -->
    <div class="main-content">
      <!-- 左侧知识点树 -->
      <div class="knowledge-tree-section">
        <div class="tree-header">
          <h3>知识点目录</h3>
          <el-select v-model="selectedCourseId" placeholder="选择课程" @change="loadKnowledgePoints" class="course-selector">
            <el-option
              v-for="course in courses"
              :key="course.courseId"
              :label="course.course_name"
              :value="course.courseId">
            </el-option>
          </el-select>
        </div>

        <div class="tree-content" v-loading="treeLoading">
          <div v-if="knowledgeTree.length === 0 && !treeLoading" class="empty-tree">
            <el-empty description="暂无知识点数据" />
          </div>
          
          <div v-else class="knowledge-tree">
            <div
              v-for="chapter in knowledgeTree"
              :key="chapter.pointId"
              class="chapter-item"
            >
              <div 
                class="chapter-title"
                @click="toggleChapter(chapter.pointId)"
                :class="{ 'expanded': expandedChapters.includes(chapter.pointId) }"
              >
                <i class="el-icon-arrow-right expand-icon"></i>
                <span class="chapter-name">{{ chapter.pointName }}</span>
                <span class="question-count">({{ chapter.questionCount || 0 }}题)</span>
              </div>
              
              <div 
                v-show="expandedChapters.includes(chapter.pointId)"
                class="sections-container"
              >
                <div
                  v-for="section in chapter.sections"
                  :key="section.pointId"
                  class="section-item"
                  :class="{ 'active': selectedPointId === section.pointId }"
                  @click="selectKnowledgePoint(section)"
                >
                  <div class="section-content">
                    <span class="section-name">{{ section.pointName }}</span>
                    <span class="section-question-count">({{ section.questionCount || 0 }}题)</span>
                  </div>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>

      <!-- 右侧知识点详情 -->
      <div class="knowledge-detail-section">
        <!-- 右侧知识点详情顶部：课程知识点进度 -->
        <div v-if="selectedCourseId" class="course-progress-info">
          <!-- 大号进度条 -->
          <el-progress
            :percentage="courseProgress"
            :text-inside="true"
            stroke-width="18"
            :status="progressStatus"
            class="course-progress-bar"
          />
          <!-- 鼓励标语 -->
          <div class="encouragement">{{ encouragementMessage }}</div>
        </div>

        <div v-if="!selectedKnowledgePoint" class="no-selection">
          <el-empty description="请从左侧选择知识点" />
        </div>

        <div v-else class="knowledge-detail">
          <!-- 知识点信息 -->
          <div class="detail-header">
            <h3 class="point-title">{{ selectedKnowledgePoint.pointName }}</h3>
            <div class="point-meta">
              <el-tag type="info" size="small">{{ getCourseNameById(selectedKnowledgePoint.courseId) }}</el-tag>
              <el-tag type="success" size="small">Level {{ selectedKnowledgePoint.level }}</el-tag>
            </div>
          </div>

          <!-- 练习统计 -->
          <div class="practice-stats">
            <h4>练习统计</h4>
            <div class="stats-grid">
              <!-- 总题数 -->
              <div class="stat-card">
                <div class="stat-number">{{ selectedKnowledgePoint.questionCount || 0 }}</div>
                <div class="stat-label">总题数</div>
              </div>
              <!-- 练习次数 -->
              <div class="stat-card">
                <div class="stat-number">{{ selectedKnowledgePoint.practiceCount || 0 }}</div>
                <div class="stat-label">练习次数</div>
              </div>
              <!-- 平均正确率 -->
              <div class="stat-card">
                <div class="stat-number">{{ selectedKnowledgePoint.correctRate || 0 }}%</div>
                <div class="stat-label">平均正确率</div>
              </div>
            </div>
          </div>

          <!-- 操作按钮 -->
          <div class="action-section">
            <el-button 
              type="primary" 
              size="large" 
              @click="startPractice"
              :disabled="(selectedKnowledgePoint.questionCount || 0) === 0"
              class="practice-btn"
            >
              <i class="el-icon-edit"></i>
              开始练习
            </el-button>
          </div>

          <!-- 最近练习记录 -->
          <div class="recent-practice" v-if="recentPractices.length > 0">
            <h4>最近练习记录</h4>
            <div class="practice-list">
              <div 
                v-for="practice in recentPractices" 
                :key="practice.id"
                class="practice-record"
              >
                <div class="practice-info">
                  <span class="practice-date">{{ formatDate(practice.create_time) }}</span>
                  <span class="practice-score">正确率: {{ practice.correct_rate }}%</span>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import { ref, reactive, computed, onMounted, watch } from 'vue'
import { ElMessage } from 'element-plus'
import { useRouter, useRoute } from 'vue-router'
import axios from 'axios'
import { useUserStore } from '../../../store/UserStore'

export default {
  name: 'KnowledgePointSelection',
  setup() {
    const router = useRouter()
    const route = useRoute()
    const userStore = useUserStore();
    const userId = userStore.userInfo?.userId || 0

    // 响应式数据
    const courses = ref([])
    // 先定义课程列表，便于初始化 selectedCourseId
    const defaultCourses = [
      { courseId: 1, course_name: '数据结构' },
      { courseId: 2, course_name: '操作系统' },
      { courseId: 3, course_name: '计算机组成系统' },
      { courseId: 4, course_name: '计算机网络' },
    ]
    // 用路由参数初始化 selectedCourseId
    const selectedCourseId = ref(Number(route.query.courseId) || defaultCourses[0].courseId)

    const knowledgePoints = ref([])
    const selectedPointId = ref(null)
    const selectedKnowledgePoint = ref(null)
    const expandedChapters = ref([])
    const treeLoading = ref(false)
    const recentPractices = ref([])
    const courseProgress = ref(0)

    // API 调用函数
    const api = {
       getPracticeStats: (userId, pointId) =>
    axios.get('/userPractices/statistics', { params: { userId, pointId } }),
  getPracticeSummary: (userId, pointId) =>
    axios.get('/userPractices/summary', { params: { userId, pointId } }),

      // 获取所有课程
      getCourses: () => axios.get('/course/all'),
      
      // 根据课程ID获取知识点
      getKnowledgePointsByCourse: (courseId) => 
        axios.get(`/KnowledgePoint/course?courseId=${courseId}`),
      
      // 获取单个知识点详情
      getKnowledgePointById: (pointId) => 
        axios.get(`/KnowledgePoint/findById?pointId=${pointId}`),
      
      // 根据知识点ID获取题目数量
      getQuestionCountByPoint: (pointId) => 
        axios.get(`/question/getbypid?pointId=${pointId}`),
      
      // 获取最近练习记录（这个接口可能需要后端实现）
      getRecentPractices: (pointId) => 
        axios.get(`/practice/recent?pointId=${pointId}`)
    }

    // 计算属性
    const knowledgeTree = computed(() => {
      if (!knowledgePoints.value.length) return []

      // 解析知识点名称，构建树形结构
      const chapters = new Map()
      
      knowledgePoints.value.forEach(point => {
        const name = point.pointName
        
        // 提取章节信息（假设格式为："第1章 绪论 - 1.1 数据结构的基本概念"）
        if (typeof name === 'string') {
  const chapterMatch = name.match(/第(\d+)章\s*([^-]+)/)
        if (chapterMatch) {
          const chapterNum = chapterMatch[1]
          const chapterTitle = chapterMatch[2].trim()
          const chapterKey = `第${chapterNum}章 ${chapterTitle}`
          
          if (!chapters.has(chapterKey)) {
            chapters.set(chapterKey, {
              pointId: `chapter_${chapterNum}`,
              pointName: chapterKey,
              sections: [],
              questionCount: 0
            })
          }
          
          // 将当前知识点作为章节下的小节
          const chapter = chapters.get(chapterKey)
          chapter.sections.push({
            ...point,
            questionCount: point.questionCount || 0
          })
          chapter.questionCount += (point.questionCount || 0)
        } else {
          // 如果不符合章节格式，作为独立项处理
          chapters.set(name, {
            ...point,
            sections: [],
            questionCount: point.questionCount || 0
          })
        }}
      })

      return Array.from(chapters.values())
    })

    // 根据 progress 值决定进度条状态（success/exception/warning）
    const progressStatus = computed(() => {
      if (courseProgress.value >= 80) return 'success'
      if (courseProgress.value >= 50) return 'warning'
      return 'exception'
    })

    // 根据不同进度生成鼓励标语
    const encouragementMessage = computed(() => {
      const p = courseProgress.value
      if (p >= 80) return '👏 太棒了！知识点掌握度很高，继续保持！'
      if (p >= 50) return '👍 不错哦！继续努力，马上就会更进一步！'
      return '💪 加油，你可以的！先攻克一些知识点吧！'
    })

    // 工具函数
    const getCourseNameById = (courseId) => {
      const course = courses.value.find(c => c.courseId === courseId)
      return course ? course.course_name : '未知课程'
    }

    const formatDate = (dateString) => {
      return new Date(dateString).toLocaleDateString('zh-CN')
    }

    // 数据加载
    const loadCourses = async () => {
      try {
        // 实际应从API获取，这里用默认
        courses.value = defaultCourses
      } catch (error) {
        console.error('加载课程失败:', error)
        ElMessage.error('加载课程失败')
      }
    }

    // 修改 loadKnowledgePoints 支持传参
    const loadKnowledgePoints = async (courseId = selectedCourseId.value) => {
      if (!courseId) return
      try {
        treeLoading.value = true
        const response = await api.getKnowledgePointsByCourse(courseId)
        const points = response.data?.data || response.data || []
        // 为每个知识点获取题目数量
        const pointsWithCount = await Promise.all(
          points.map(async (point) => {
            try {
              const questionsResponse = await api.getQuestionCountByPoint(point.pointId)
              const questions = questionsResponse.data?.data || questionsResponse.data || []
              return {
                ...point,
                questionCount: questions.length
              }
            } catch (error) {
              return {
                ...point,
                questionCount: 0
              }
            }
          })
        )
        knowledgePoints.value = pointsWithCount
        // 默认展开第一个章节
        if (knowledgeTree.value.length > 0) {
          expandedChapters.value = [knowledgeTree.value[0].pointId]
          // 自动选中第一个知识点
          if (knowledgeTree.value[0].sections?.length) {
            selectKnowledgePoint(knowledgeTree.value[0].sections[0])
          }
        }
      } catch (error) {
        ElMessage.error('加载知识点失败')
      } finally {
        treeLoading.value = false
      }
    }

    const loadKnowledgePointDetail = async (pointId) => {
  try {
    // 1. 获取知识点详情
    const response = await api.getKnowledgePointById(pointId);
    const pointDetail = response.data?.data || response.data;
    if (!pointDetail) throw new Error('未找到该知识点');

    // 2. 获取该知识点下的题目数
    const questionsResponse = await api.getQuestionCountByPoint(pointId);
    const questionCount = (questionsResponse.data?.data || questionsResponse.data || []).length;

    // 3. 获取练习统计：练习次数 + 平均正确率
    const userId = userStore.userInfo.userId; // 从 pinia/store 拿当前用户ID
    let practiceCount = 0, correctRate = 0;
    try {
      // 可以选用 summary 接口，也可用 statistics
      const statsRes = await api.getPracticeSummary(userId, pointId);
      const stats = statsRes.data; // { practiceCount: int, accuracy: double }
      practiceCount = stats.practiceCount;
      correctRate = Math.round(stats.accuracy * 100); // 转成百分比
    } catch (e) {
      console.warn('获取练习统计失败', e);
    }

    // 4. 合并到响应式对象
    selectedKnowledgePoint.value = {
      ...pointDetail,
      questionCount,
      practiceCount,
      correctRate
    };

  } catch (error) {
    console.error('加载知识点详情失败:', error);
    ElMessage.error('加载知识点详情失败');
  }
};


    // 拉取当前课程的知识点掌握进度
    const loadCourseProgress = async () => {
      if (!selectedCourseId.value) return
      try {
        const { data } = await axios.get('/userPractices/point-progress', {
          params: { userId, courseId: selectedCourseId.value }
        })
        if (Object.prototype.hasOwnProperty.call(data, 'progress')) {
          courseProgress.value = Math.round(data.progress)
        } else {
          const { practicedCount, totalCount } = data
          courseProgress.value = totalCount ? Math.round((practicedCount / totalCount) * 100) : 0
        }
      } catch (e) {
        courseProgress.value = 0
      }
    }

    // 交互操作
    const toggleChapter = (chapterId) => {
      const index = expandedChapters.value.indexOf(chapterId)
      if (index > -1) {
        expandedChapters.value.splice(index, 1)
      } else {
        expandedChapters.value.push(chapterId)
      }
    }

    const selectKnowledgePoint = async (point) => {
      selectedPointId.value = point.pointId
      await loadKnowledgePointDetail(point.pointId)
      
      // 加载最近练习记录
      try {
        // const practicesResponse = await api.getRecentPractices(point.pointId)
        // recentPractices.value = practicesResponse.data?.data || []
        recentPractices.value = [] // 暂时为空，等后端实现
      } catch (error) {
        console.error('加载练习记录失败:', error)
        recentPractices.value = []
      }
    }

    const startPractice = () => {
      if (!selectedKnowledgePoint.value) {
        ElMessage.warning('请先选择知识点')
        return
      }

      if ((selectedKnowledgePoint.value.questionCount || 0) === 0) {
        ElMessage.warning('该知识点暂无题目')
        return
      }

      // 跳转到练习页面，传递知识点ID
      router.push({
        name: 'Practice408',
        query: { 
          pointId: selectedKnowledgePoint.value.pointId,
          subject: getCourseNameById(selectedKnowledgePoint.value.courseId)
        }
      })
    }

    // 生命周期
    // 监听 selectedCourseId 变化，自动加载
    watch(selectedCourseId, (cid) => {
      loadKnowledgePoints(cid)
      loadCourseProgress()
    })
    // 监听路由参数变化
    watch(() => route.query.courseId, (newId) => {
      const cid = Number(newId) || defaultCourses[0].courseId
      selectedCourseId.value = cid
    })

    onMounted(async () => {
      await loadCourses()
      await loadKnowledgePoints(selectedCourseId.value)
      await loadCourseProgress()
    })

    return {
      // 数据
      courses,
      selectedCourseId,
      knowledgePoints,
      selectedPointId,
      selectedKnowledgePoint,
      expandedChapters,
      treeLoading,
      recentPractices,
      courseProgress,
      // 计算属性
      knowledgeTree,
      progressStatus,
      encouragementMessage,
      // 方法
      getCourseNameById,
      formatDate,
      loadKnowledgePoints,
      toggleChapter,
      selectKnowledgePoint,
      startPractice
    }
  }
}
</script>

<style scoped>
/* 美化知识点选择页面，优化配色、卡片、按钮、阴影、圆角、动画、响应式等 */
.knowledge-point-container {
  background: linear-gradient(135deg, #f9f8ff 0%, #e3f0ff 100%);
  min-height: 100vh;
  padding: 32px 0 32px 0;
  display: flex;
  flex-direction: column;
  align-items: center;
}

.header-section {
  width: 90%;
  max-width: 1100px;
  margin-bottom: 18px;
  background: #fff;
  border-radius: 18px;
  box-shadow: 0 4px 24px 0 rgba(99,143,255,0.10);
  padding: 18px 32px 12px 32px;
  display: flex;
  flex-direction: column;
  align-items: stretch;
}

.header-content {
  display: flex;
  align-items: center;
  gap: 18px;
}

.back-btn {
  color: #4b67d6;
  font-weight: bold;
  font-size: 16px;
}

.page-title {
  font-size: 22px;
  font-weight: bold;
  color: #6f84d5;
  margin-left: 12px;
}

.main-content {
  width: 90%;
  max-width: 1100px;
  display: grid;
  grid-template-columns: 320px 1fr;
  gap: 32px;
  margin: 0 auto 24px auto;
  min-height: 480px;
}

/* 左侧知识点树 */
.knowledge-tree-section {
  background: #fff;
  border-radius: 18px;
  box-shadow: 0 4px 24px 0 rgba(99,143,255,0.10);
  padding: 24px 18px 18px 18px;
  min-width: 220px;
  max-width: 340px;
  display: flex;
  flex-direction: column;
  align-items: stretch;
}

.tree-header {
  display: flex;
  align-items: center;
  gap: 12px;
  margin-bottom: 12px;
}

.course-selector {
  min-width: 120px;
}

.knowledge-tree {
  margin-top: 8px;
}

.chapter-item {
  margin-bottom: 10px;
}

.chapter-title {
  display: flex;
  align-items: center;
  gap: 8px;
  font-size: 16px;
  font-weight: 500;
  color: #4e69d3;
  background: #f4f7ff;
  border-radius: 8px;
  padding: 6px 12px;
  cursor: pointer;
  transition: background 0.2s;
}

.chapter-title.expanded {
  background: #e3f0ff;
}

.expand-icon {
  transition: transform 0.2s;
}

.chapter-title.expanded .expand-icon {
  transform: rotate(90deg);
}

.chapter-name {
  flex: 1;
}

.question-count {
  color: #888;
  font-size: 13px;
}

.sections-container {
  margin-left: 18px;
  margin-top: 4px;
}

.section-item {
  background: #f9f8ff;
  border-radius: 8px;
  padding: 6px 12px;
  margin-bottom: 4px;
  cursor: pointer;
  transition: background 0.2s, color 0.2s;
  color: #333;
}

.section-item.active {
  background: #6176cb;
  color: #fff;
  font-weight: bold;
}

.section-content {
  display: flex;
  align-items: center;
  gap: 8px;
}

.section-name {
  flex: 1;
}

.section-question-count {
  color: #888;
  font-size: 13px;
}

/* 右侧知识点详情 */
.knowledge-detail-section {
  background: #fff;
  border-radius: 18px;
  box-shadow: 0 4px 24px 0 rgba(99,143,255,0.10);
  padding: 32px 32px 24px 32px;
  min-height: 400px;
  display: flex;
  flex-direction: column;
  animation: fadeIn 0.3s ease-in;
}

.no-selection {
  display: flex;
  align-items: center;
  justify-content: center;
  height: 100%;
}

.knowledge-detail {
  display: flex;
  flex-direction: column;
  gap: 18px;
}

.detail-header {
  display: flex;
  align-items: center;
  gap: 18px;
  margin-bottom: 8px;
}

.point-title {
  font-size: 20px;
  font-weight: bold;
  color: #5a6bb2;
}

.point-meta {
  display: flex;
  gap: 10px;
}

.detail-content {
  background: #f9f8ff;
  border-radius: 12px;
  padding: 18px 24px;
  color: #333;
  font-size: 15px;
  margin-top: 8px;
  box-shadow: 0 2px 8px 0 rgba(99,143,255,0.06);
}

.description-section h4 {
  color: #6279d1;
  font-size: 15px;
  margin-bottom: 4px;
}

.description-text {
  color: #555;
  font-size: 15px;
  margin-bottom: 10px;
}

.practice-stats h4 {
  color: #6881e6;
  font-size: 15px;
  margin-bottom: 8px;
}

.stats-grid {
  display: flex;
  gap: 18px;
  margin-bottom: 10px;
  justify-content: center; /* 水平居中卡片 */
  align-items: center;    /* 垂直居中卡片（如高度不一致）*/
}

.stat-card {
  background: #f4f7ff;
  border-radius: 10px;
  padding: 18px 24px;
  text-align: center;
  min-width: 90px;
  box-shadow: 0 2px 8px 0 rgba(99,143,255,0.06);
}

.stat-number {
  font-size: 22px;
  color: #6576ba;
  font-weight: bold;
  margin-bottom: 4px;
}

.stat-label {
  color: #888;
  font-size: 14px;
}

.action-section {
  display: flex;
  gap: 16px;
  margin-bottom: 18px;
}

.practice-btn {
  flex: 1;
}

.el-button {
  border-radius: 8px !important;
  font-size: 15px !important;
  padding: 7px 22px !important;
  font-weight: 500;
}

.recent-practice h4 {
  color: #647ad3;
  font-size: 15px;
  margin-bottom: 8px;
}

.practice-list {
  max-height: 200px;
  overflow-y: auto;
}

.practice-record {
  background: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 8px 0 rgba(99,143,255,0.06);
  padding: 12px 18px;
  margin-bottom: 8px;
  display: flex;
  align-items: center;
  justify-content: space-between;
}

.practice-info {
  display: flex;
  justify-content: space-between;
  align-items: center;
  width: 100%;
}

.practice-date {
  color: #888;
  font-size: 13px;
}

.practice-score {
  color: #3bbd3b;
  font-size: 13px;
  font-weight: 500;
}

.course-progress-info {
  display: flex;
  flex-direction: column;
  align-items: center;
  margin-bottom: 20px;
}

.course-progress-bar {
  width: 80%;
  min-width: 240px;
}

.encouragement {
  margin-top: 8px;
  font-size: 16px;
  font-weight: 500;
  color: #2c3e50;
  text-align: center;
}

@media (max-width: 900px) {
  .main-content {
    grid-template-columns: 1fr;
    gap: 18px;
  }
  .knowledge-tree-section, .knowledge-detail-section {
    max-width: 100%;
    width: 100%;
  }
}

/* 动画效果 */
.knowledge-detail-section {
  animation: fadeIn 0.3s ease-in;
}
@keyframes fadeIn {
  from {
    opacity: 0;
    transform: translateY(10px);
  }
  to {
    opacity: 1;
    transform: translateY(0);
  }
}
</style>